/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * email:nur01@qq.com
 * @flow
 */

import React, {Component} from 'react';
import {
    Alert,
    DeviceEventEmitter,
    Image,
    ListView,
    Platform,
    RefreshControl,
    StyleSheet,
    Switch,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import Navigation from "../../../custom/Navigation";
import ModalBottomUtils from "../../../utils/ModalBottomUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import RecommendedIBM from "./RecommendedIBM";
import I18n from "../../../res/language/i18n";
import AlertDialog from "../../../custom/AlertDialog";
import IparInput from "../../../custom/IparInput";
import MandatoryProductPage from "../MandatoryProductPage";

const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

let positionData = [];
export default class RegisterIBMThreePage extends Component {
    constructor(props) {
        super(props);


        this.sponsorKeyInput = '';
        this.sponsorIdInput = '';
        this.directSponsorId = '';
        this.resultData = [];


        let userPosition = [];
        let rank = this.props.selectPlan ? this.props.selectPlan.rank : -1;

        if (rank === 5 || rank === 6) {//3个位置
            userPosition = [
                {rank_name: I18n.t('b.right'), userPositionCode: 'R'},
                {rank_name: I18n.t('b.left'), userPositionCode: 'L'},
            ]
        }
        positionData = userPosition;

        this.state = {
            modalDataSource: ds,
            userPositionData: userPosition,
            falseSwitchIsOn: true,
            userPositionCode: '',
            userPositionName: '',
            modalDialog: false,
            modalDialogTypeIsRank: true,
            // showLoading: false,
            marketingPlan: this.props.selectPlan ? this.props.selectPlan.rank_name : null,
            marketingRank: rank,
            userID: '',
            sponsorId: '',
            ibmRank: '',
            parentPosition: '',
            parentId: '',
            ibmCode: null,
            showDialog: false,
            showDialogType: false,
            leftDialog: false,
            dialogContent: '',

        };
        this.iparNetwork = new IparNetwork();
    }

    componentWillUnmount() {
        this.iparNetwork = null;
        this.sponsorKeyInput = null;
        this.sponsorIdInput = null;
        this.resultData = null;
    }


    componentDidMount() {

        //来自register tow....

        if (this.props.userId) {
            this.setState({
                userID: this.props.userId
            });
            this.country = this.props.country;
            this.getMarketingPlan();
        } else {
            CommonUtils.getAcyncInfo('userInfo')
                .then((userInfo) => {
                    CommonUtils.getAcyncInfo('country_iso')
                        .then((result) => {

                            let parse = JSON.parse(userInfo);

                            this.setState({
                                userID: parse.main_user_id,
                            });
                            this.country = result;
                            this.getMarketingPlan();
                        });
                });
        }


    }

    /*获取奖励计划信息*/
    getMarketingPlan() {
        if (this.props.selectPlan) {

            return;
        }

        this.setState({
            showLoading: false
        });

        let coun = this.country === 'CN' ? 1 : 2;
        let rankArr = [];
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getRank?', 'country=' + this.country)// coun + '&status=0'
            .then((result) => {
                this.setState({showLoading: false});
                if (result.code === 200) {
                    for (i = 0; i < result.data.length; i++) {
                        if (result.data[i].rank !== 1) {
                            rankArr.push(result.data[i])
                        }
                    }

                    this.setState({
                        modalDataSource: this.state.modalDataSource.cloneWithRows(rankArr),
                    })
                }

            }).catch((error) => {
            console.log(error);
            this.setState({showLoading: false})
        })
    }

    /**搜索推荐人信息*/
    getSearchSponsor(value) {
        this.setState({
            showLoading: true,
        });

        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'searchSponsor?', 'keywords=' + value + '&rank=' + this.state.marketingRank)
            .then((result) => {
                this.setState({showLoading: false});
                if (result.code === 200) {
                    let data = result.data;
                    console.log(data);
                    if (data.rank === this.state.marketingRank) {

                        let _userName = data.first_name;
                        let _mobile = data.mobile;

                        let userMain = data.user_main;

                        if (userMain) {
                            _userName = ((userMain.first_name || '') + (userMain.family_name || '')) || (userMain.nick_name);
                            _mobile = userMain.mobile ? userMain.mobile : _mobile
                        }
                        this.setState({
                            dialogContent: I18n.t('default.userName') + ': ' + (_userName || '') + '\n' +
                                I18n.t('default.phone') + ': ' + (_mobile || ''),
                            leftDialog: true,
                            sponsorId: this.sponsorIdInput,
                            showLoading: false,
                        });
                        this.resultData = data;

                    } else {
                        this.setState({
                            showDialog: true,
                            showDialogType: false,
                            showLoading: false,
                            dialogContent: I18n.t('default.noReferee')
                        });

                    }
                } else {
                    this.setState({
                        showDialog: true,
                        showDialogType: false,
                        showLoading: false,
                        dialogContent: I18n.t('default.noReferee')
                    });
                }

            }).catch((error) => {
            console.log(error);
            this.setState({showLoading: false})
        })
    }

    /**
     * 编辑用户商务信息
     * */
    getIbm() {
        CommonUtils.showLoading();
        let formData = new FormData();
        let state = this.state;
        formData.append("main_user_id", state.userID);
        formData.append("rank", state.ibmRank);
        formData.append("keywords", state.sponsorId);
        formData.append("code", state.ibmCode);
        formData.append("country", this.country);
        formData.append('froms', Platform.OS === 'ios' ? 'IOS' : 'Android');
        state.userPositionCode && formData.append("position", state.userPositionCode);
        this.directSponsorId && formData.append("sponsor", this.directSponsorId);

        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'openSubAccount', formData)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    this.newUserData = result.data;
                    this.setState({
                        showDialog: true,
                        showDialogType: true,
                        dialogContent: I18n.t('registerContractModal.registerSuccessfulIBMEnd')
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }

                console.log(result)
            })
            .catch((error) => {
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log(error);
                CommonUtils.dismissLoading();
            })
    }

    /**
     * 条第二个注册页面
     */
    startNex() {
        let state = this.state;
        if (state.falseSwitchIsOn) {
            if (state.marketingPlan === null) {
                DeviceEventEmitter.emit('toast', I18n.t('default.chooseMarketingPlan'))
            } else if ((this.state.marketingRank === 9 || state.userPositionData.length > 0) && !this.directSponsorId.trim()) {
                DeviceEventEmitter.emit('toast', I18n.t('default.directSponsorId'))
            } else if (state.ibmCode === null) {
                DeviceEventEmitter.emit('toast', I18n.t('default.sponsorId'))
            } else if (this.sponsorKeyInput.trim() === '') {
                DeviceEventEmitter.emit('toast', I18n.t('default.sponsorKey'))
            } else if (state.sponsorId !== this.sponsorIdInput) {
                DeviceEventEmitter.emit('toast', I18n.t('default.sponsorId'))
            } else if (state.userPositionData.length > 0 && !state.userPositionCode) {
                DeviceEventEmitter.emit('toast', 'select position')
            } else if (state.ibmCode === this.sponsorKeyInput) {
                this.getIbm()
            } else {
                DeviceEventEmitter.emit('toast', I18n.t('b.sponsorKeyError'))
            }
        } else {
            if (state.marketingRank === null) {
                DeviceEventEmitter.emit('toast', I18n.t('default.chooseMarketingPlan'));
                return;
            }
            this.props.navigator.push({
                component: RecommendedIBM,
                name: 'RecommendedIBM',
                params: {
                    country: this.country,
                    rank: state.marketingRank,
                }
            })

        }


        // this.props.navigator.push({
        // this.props.navigator.push({
        // 	component: RegisterIBMFourPage
        // })

    }

    /*modalBottom 关*/
    hiddenDialog() {
        this.setState({modalDialog: false})
    }

    render() {

        let state = this.state;
        let personalLabel = (state.falseSwitchIsOn ?
                <View>
                    {(this.state.marketingRank === 8 || this.state.marketingRank === 9 || positionData.length > 0) &&
                    <View>
                        <Text style={{color: '#999', marginTop: 16}}>{I18n.t('default.directSponsorId')}</Text>
                        <IparInput
                            onBlur={() => this.getSearchSponsor(this.directSponsorId)}
                            style={{marginTop: 0}}
                            onChangeText={(value) => {
                                this.directSponsorId = value;
                            }}
                            placeholder={I18n.t('default.directSponsorId')}/>
                    </View>}

                    <Text style={{color: '#999', marginTop: 16}}>{I18n.t('default.sponsorId')}</Text>

                    <View style={[StyleUtils.justifySpace, StyleUtils.center]}>
                        <IparInput
                            onBlur={() => this.getSearchSponsor(this.sponsorIdInput)}
                            onChangeText={(value) => {
                                this.sponsorIdInput = value;
                            }}
                            placeholder={I18n.t('default.sponsorId')}/>


                        {/*{ViewUtils.getButton(I18n.t('default.check'), () => {*/}
                        {/*if (this.state.marketingRank !== null) {*/}
                        {/*if (this.sponsorIdInput === '') {*/}
                        {/*DeviceEventEmitter.emit('toast', I18n.t('default.sponsorId'))*/}
                        {/*} else {*/}
                        {/*;*/}
                        {/*}*/}
                        {/*} else {*/}
                        {/*DeviceEventEmitter.emit('toast', I18n.t('default.chooseMarketingPlan'))*/}
                        {/*}*/}


                        {/*}, {width: '30%'})}*/}
                    </View>

                    <Text style={{color: '#999', marginTop: 16}}>{I18n.t('default.sponsorKey')}</Text>
                    <IparInput
                        style={{marginTop: 0}}
                        onChangeText={(value) => {
                            this.sponsorKeyInput = value;
                        }}
                        placeholder={I18n.t('default.sponsorKey')}/>


                    {state.userPositionData.length > 0 ?
                        ViewUtils.getButtunMenu(state.userPositionName ? state.userPositionName : I18n.t('b.selectPosition'), () => {
                            this.setState({
                                modalDialog: true,
                                modalDialogTypeIsRank: false,
                            })
                        }, StyleUtils.marginTop)
                        : null}

                </View> : null
        );

        let resultData = this.resultData;
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                    onClickLeftBtn={() => {
                        if (this.props.userId) {//来自：register ibm tow page
                            new CommonUtils().popToRoute(this, 'LoginPage')
                        } else {
                            this.props.navigator.pop()
                        }
                    }}
                />
                <ModalBottomUtils
                    visible={state.modalDialog}
                    dataSource={state.modalDialogTypeIsRank ? state.modalDataSource : ds.cloneWithRows(state.userPositionData)}
                    requestClose={this.hiddenDialog.bind(this)}
                    renderRow={this.modalRow.bind(this)}
                    title={state.modalDialogTypeIsRank ? I18n.t('default.chooseMarketingPlan') : I18n.t('b.selectPosition')}
                />
                <AlertDialog
                    visible={state.showDialog}
                    requestClose={() => this.setState({showDialog: false})}
                    contentTv={state.dialogContent}
                    singleBtnOnclick={() => {
                        this.setState({
                            showDialog: false,
                        });
                        if (this.state.showDialogType) {
                            if (this.props.userId) {//来自：register ibm tow page
                                new CommonUtils().popToRoute(this, 'LoginPage')
                            } else {
                                const {navigator} = this.props;
                                DeviceEventEmitter.emit('upDateUserData', this.newUserData);
                                DeviceEventEmitter.emit('toast', I18n.t('default.ibmUpgrade'));
                                // navigator.popToTop();
                                navigator.push({
                                    component: MandatoryProductPage,
                                    name: 'MandatoryProductPage',
                                    params: {
                                        userData: this.newUserData,
                                    }
                                })
                            }
                        }
                    }}
                    centerSts={I18n.t('default.ok')}
                />
                <AlertDialog
                    visible={state.leftDialog}
                    requestClose={() => this.setState({leftDialog: false})}
                    contentTv={state.dialogContent}
                    leftBtnOnclick={() => {

                        let userPositionData = CommonUtils.cloneArray(positionData);
                        if (this.resultData.use_position !== null) {
                            for (let i = 0, len = userPositionData.length; i < len; i++) {
                                if (this.resultData.use_position.indexOf(userPositionData[i].userPositionCode) !== -1) {
                                    userPositionData[i] = null;
                                }
                            }
                        }


                        this.setState({
                            leftDialog: false,
                            parentId: this.resultData.main_user_id,
                            ibmRank: this.resultData.rank,
                            ibmCode: this.resultData.code,
                            parentPosition: this.resultData.use_position,
                            userPositionName: '',
                            userPositionData: userPositionData,
                        })
                    }}


                />
                <KeyboardAwareScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={state.showLoading}
                            onRefresh={() => {
                            }}
                        />
                    }
                >
                    <View style={{padding: 16}}>
                        {/*title*/}
                        {ViewUtils.getTitleView(I18n.t('default.activateMarketing') + (state.marketingPlan || I18n.t('default.businessPlan')), I18n.t('default.marketingPlanThatSuits'))}


                        {!this.props.selectPlan ? ViewUtils.getButtunMenu(state.marketingPlan ? state.marketingPlan : I18n.t('default.chooseMarketingPlan'), () => {
                                this.setState({
                                    modalDialog: true,
                                    modalDialogTypeIsRank: true,
                                })
                            }) :
                            null
                        }


                        <View style={[StyleUtils.justifySpace, StyleUtils.marginTop]}>
                            <Text style={[StyleUtils.text, StyleUtils.smallFont]}>{I18n.t('default.haveSponsor')}</Text>
                            <Switch
                                onTintColor={'#333333'}
                                thumbTintColor={Platform.OS === 'ios' ? null : 'white'}
                                onValueChange={(value) => this.setState({falseSwitchIsOn: value})}
                                value={state.falseSwitchIsOn}/>
                        </View>

                        {personalLabel}

                        {ViewUtils.getButton(I18n.t('default.next'), () => this.startNex(), [{marginBottom: 40}, StyleUtils.marginTop])}
                        <Text style={StyleUtils.smallFont}>{I18n.t('default.canActivateYourPlan')}</Text>
                    </View>
                </KeyboardAwareScrollView>
            </View>
        );
    }


    /*modalBottom list renderRow*/
    modalRow(rowData, sectionID, rowID) {

        return (<View>
                {!rowData ? null :


                    <TouchableOpacity
                        activeOpacity={0.5}
                        onPress={() => {
                            if (this.state.modalDialogTypeIsRank) {
                                positionData = [];
                                let userPosition = [];

                                if (rowData.rank === 5 || rowData.rank === 6) {//3个位置
                                    userPosition = [
                                        {rank_name: I18n.t('b.right'), userPositionCode: 'R'},
                                        {rank_name: I18n.t('b.left'), userPositionCode: 'L'},
                                    ]
                                }

                                // if (rowData.rank === 5) {//3个位置
                                // 	userPosition = [
                                // 		{rank_name: 'right', userPositionCode: 'R'},
                                // 		{rank_name: 'center', userPositionCode: 'C'},
                                // 		{rank_name: 'left', userPositionCode: 'L'},
                                // 	]
                                // } else if (rowData.rank === 6) {//2位置
                                // 	userPosition = [
                                // 		{rank_name: 'right', userPositionCode: 'R'},
                                // 		{rank_name: 'left', userPositionCode: 'L'},
                                // 	]
                                // }

                                positionData = userPosition;
                                this.setState({
                                    marketingPlan: rowData.rank_name,
                                    marketingRank: rowData.rank,
                                    userPositionData: userPosition,
                                });
                            } else {
                                this.setState({
                                    userPositionCode: rowData.userPositionCode,
                                    userPositionName: rowData.rank_name,
                                });
                            }

                            this.hiddenDialog();
                        }}
                        style={[StyleUtils.listItem, StyleUtils.center, StyleUtils.rowDirection]}
                    >
                        <Text
                            style={[StyleUtils.flex, StyleUtils.smallFont, {
                                fontSize: 16,
                                color: 'black',
                                textAlign: 'center',
                            }]}>{rowData.rank_name}</Text>
                    </TouchableOpacity>
                }
            </View>

        )
    }
}




